package com.lpf.example.example05;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {

        ChannelPipeline pipeline = ch.pipeline();

        // websocket是基于http的，所以要有http相关的编解码器
        pipeline.addLast(new HttpServerCodec())
                // 以块的方式写的处理器
                .addLast(new ChunkedWriteHandler())
                // 聚合HttpMessage和HttpContent成一个FullHttpRequest或FullHttpResponse（基于netty的http编程中使用的非常多）
                .addLast(new HttpObjectAggregator(8192))
                // ws即websocket协议
                // ws://server:port/context_path
                // ws://localhost:8899/'ws' WebSocketServerProtocolHandler的ws是指请求地址里的第二个ws
                .addLast(new WebSocketServerProtocolHandler("/ws"))
                // 自定义处理器
                .addLast(new TextWebSocketFrameHandler());

    }
}
